import { CdkDragDrop, moveItemInArray } from '@angular/cdk/drag-drop';
import { Component, OnInit, ViewChild } from '@angular/core';
import { TreetableComponent, TreeTableNode, lvFlattenTreeData } from '@iux/live';
import { Subject } from 'rxjs';
import { startWith, takeUntil } from 'rxjs/operators';
import { TreetableService } from '../tree-table.service';

@Component({
  selector: 'app-virtual-scroll-drag',
  templateUrl: './virtual-scroll-drag.component.html',
  styles: [
    `
      .app-custom-placeholder {
        background: #ccc;
        border: dotted 3px #999;
        height: 48px;
        transition: transform 250ms cubic-bezier(0, 0, 0.2, 1);
      }
    `,
  ],
})
export class VirtualScrollDragComponent implements OnInit {
  data: TreeTableNode[];

  @ViewChild('lvTreeTable', { static: true }) lvTreeTable: TreetableComponent;

  private treeTableDestroy$ = new Subject<void>();

  constructor(private treetableService: TreetableService) {}

  ngOnInit() {
    this.initAsyncData();
  }

  ngAfterViewInit() {
    this.subscribeRenderChange();
  }

  drop(event: CdkDragDrop<string[]>) {
    const dragData = event.item.data.parent.children;
    const index = this.lvTreeTable.renderData.findIndex(item => item.data.data.id === event.item.data.parent.data.data.id) + 1;
    // user4的子级40和41交换了顺序变成41 40，然后再次展开user5，会导致user4的子级变成40、41。故需要同时更改flattenData和dragData
    const flattenData = this.lvTreeTable.renderData;
    moveItemInArray(flattenData, index + event.previousIndex, index + event.currentIndex);
    this.lvTreeTable.renderData = [...flattenData];
    moveItemInArray(dragData, event.previousIndex, event.currentIndex);
  }

  subscribeRenderChange() {
    this.lvTreeTable.renderDataChange$.pipe(startWith(this.lvTreeTable.renderData), takeUntil(this.treeTableDestroy$)).subscribe(() => {
      const flattenData = lvFlattenTreeData(this.lvTreeTable.renderData, null, { getNodeLevel: true });
      this.lvTreeTable.renderData = flattenData;
    });
  }

  initAsyncData() {
    this.treetableService.getUsers2().subscribe((res: TreeTableNode[]) => {
      this.data = res;
    });
  }

  trackByIndex(index) {
    return index;
  }

  stateChange(e) {
    console.log('条件发生变更', e);
  }

  expandedChange(expanded, item) {
    // data地址发生变更
    this.data = [...this.data];
    // 展开互斥
    if (expanded) {
      for (const data of this.lvTreeTable.renderData) {
        data.data.expanded = false;
      }

      item.expanded = true;
    }
  }

  ngOnDestroy(): void {
    this.treeTableDestroy$.next();
    this.treeTableDestroy$.complete();
  }
}
